/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.commons.util;

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

/**
 * 电话号码工具类
 *
 * @author liym
 * @since 2019-12-10 13:59 新建
 */
public final class PhoneNoUtil {

    private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();

    /**
     * 中国地区代码 {@value}
     */
    private static final int COUNTRY_CODE = 86;

    private PhoneNoUtil() {}

    /**
     * 判断手机号码是否合法
     *
     * @param phoneNumber 手机号码
     * @return true/false
     */
    public static boolean isValidMobilePhoneNo(String phoneNumber) {
        PhoneNumberUtil.PhoneNumberType numberType;
        try {
            Phonenumber.PhoneNumber number = new Phonenumber.PhoneNumber();
            number.setCountryCode(COUNTRY_CODE);
            number.setNationalNumber(Long.parseLong(phoneNumber));
            numberType = PHONE_NUMBER_UTIL.getNumberType(number);
        } catch (Exception e) {
            numberType = null;
        }
        return numberType == PhoneNumberUtil.PhoneNumberType.MOBILE;
    }

    /**
     * 判断电话号码是否合法
     *
     * @param phoneNumber 电话号码
     * @return true/false
     * @since 2019-12-10 14:26
     */
    public static boolean isValidPhoneNo(String phoneNumber) {
        Phonenumber.PhoneNumber number = new Phonenumber.PhoneNumber();
        try {
            number.setCountryCode(COUNTRY_CODE);
            number.setNationalNumber(Long.parseLong(phoneNumber));
        } catch (Exception ignored) {}
        return PHONE_NUMBER_UTIL.isValidNumber(number);
    }

    public static void main(String[] args) {
        System.out.println(isValidMobilePhoneNo("15899999999"));
        System.out.println(isValidPhoneNo("07975380010"));
        System.out.println(isValidPhoneNo("0797-5380010"));
    }

}
